<template>
    <div class="login zw-img-bg">
        <div class="login-panel">
            <div class="title">商城运营管理系统</div>
            <el-form
                :model="loginForm"
                :rules="loginFormRules"
                ref="loginFormRef"
                label-width="0"
                class="login-form"
                size="large">
                <el-form-item label="" prop="username">
                    <el-input v-model.trim="loginForm.username" placeholder="用户名"></el-input>
                </el-form-item>
                <el-form-item label="" prop="password">
                    <el-input type="password" v-model="loginForm.password" show-password placeholder="密码"></el-input>
                </el-form-item>
            </el-form>
            <el-form class="login-form">
                <el-form-item>
                    <el-button
                        type="primary"
                        :disabled="isDisabled"
                        size="large"
                        class="login-submit"
                        @click="loginFormHandler">
                        登 录
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script setup>
import { computed, reactive, ref, inject } from 'vue';
import request from '@/request';
import store from '@/store';
import storage from '@/commons/storage';
import { useRouter } from 'vue-router';
import { isPassword } from '@/commons/utils';

const useAuth = store.useAuthStore();
const router = useRouter();
const loginFormRef = ref(null);

const loginForm = reactive({
    username: '',
    password: ''
});

/**
 * 密码规则校验
 * @param {*} rule
 * @param {*} value
 * @param {*} callback
 */
const validatePasswordRule = (rule, value, callback) => {
    if (isPassword(value)) {
        callback();
    } else {
        callback(new Error('长度8-16个字符，由数字或字母组成且不能有特殊字符'));
    }
};

const loginFormRules = reactive({
    username: [{ required: true, message: '请输入手机号', trigger: 'blur' }],
    password: [{ required: true, message: '请输入密码', trigger: 'blur' }]
});

const isDisabled = computed(() => {
    const { username, password } = loginForm;
    return !username || !password;
});

/**
 * 用户名登录
 */
const loginFormHandler = () => {
    loginFormRef.value.validate(async valid => {
        if (valid) {
            const res = await request('loginServ', loginForm);
            loginAfterHandler(res);
        }
    });
};

/**
 * 缓存登录态并跳转
 * @param {*} res
 */
const loginAfterHandler = res => {
    const { token } = res.data;
    storage.set('ZW-TOKEN', token);
    router.push('/pay/baofu');
};
</script>
<style lang="scss" src="./style.scss" scoped></style>
